package com.imau.controller;

import com.imau.bean.User;
import com.imau.mapper.UserMapper;
import com.imau.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        System.out.println("init...");
    }

    @Override
    public void destroy() {
        System.out.println("destroy....");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //1.获取页面传递过来 用户名 和密码
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        //2.查询数据库
        SqlSession session = SqlSessionFactoryUtil.getInstace().openSession(true);
        UserMapper mapper = session.getMapper(UserMapper.class);

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);

        int i = mapper.insertUser(user);

        if(i>0)
        {
            response.sendRedirect("/servlet-loginDemo/login.html");
        }else {
            response.sendRedirect("/servlet-loginDemo/register.html");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request,response);
    }
}
